package com.rp.data.tcp_ws.server_ws;

import com.rp.data.tcp_ws.server_tcp.NettyServerTcp;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

/**
 * @ description 解决项目打war包发布在tomcat，端口被占用问题
 * 解决思路：给NettyServer分配一个独立的线程用于加载
 */
@Slf4j
@Component
public class NettyServerListener implements ApplicationListener<ContextRefreshedEvent> {

    @Autowired
    private NettyServerWs nettyServerWs;

    @Autowired
    private NettyServerTcp nettyServerTcp;

    @Value("${ws.port}")
    private Integer wsPort;

    @Value("${ws.enable}")
    private Boolean wsEnable;

    @Value("${tcp.port}")
    private Integer tcpPort;

    @Value("${tcp.enable}")
    private Boolean tcpEnable;

    /**
     * 当一个applicationContext被初始化或被刷新时触发
     *
     * @param event
     */
    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        if (event.getApplicationContext().getParent() == null) {
            log.info("NettyServer Start Success");
//            if (wsEnable) {
//                runWs();
//            }
//            if (tcpEnable) {
//                runTcp();
//            }
        }
    }

    @Async
    public void runWs() {
        System.out.println("---------异步线程---------" + Thread.currentThread().getName());
        this.nettyServerWs.start(wsPort);
    }

    @Async
    public void runTcp() {
        System.out.println("---------异步线程---------" + Thread.currentThread().getName());
        this.nettyServerTcp.start(tcpPort);
    }
}
